﻿using System.Text.Json.Serialization;

namespace System.Text.Json
{
    public class BooleanConverter : JsonConverter<Boolean>
    {
        private readonly string _trueValue;

        private readonly string _falseValue; 
        public BooleanConverter(string trueValue, string falseValue) 
        { 
            _trueValue = trueValue; 
            _falseValue = falseValue; 
        }
        public BooleanConverter()
        {
            _trueValue = "true";
            _falseValue = "false";
        }
        public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                var stringValue = reader.GetString();
                if (_trueValue.Equals(stringValue, StringComparison.OrdinalIgnoreCase))
                { 
                    return true;
                }
                else if (_falseValue.Equals(stringValue, StringComparison.OrdinalIgnoreCase))
                { 
                    return false;
                }
            } 
            throw new JsonException("Cannot convert string to boolean.");
        }

        public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value ? _trueValue : _falseValue);
        }
    }
}